package cn.cjxy.springmvcdemo1.controller;

import cn.cjxy.springmvcdemo1.domain.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**向页面传递参数的方式
 * @author huangjie
 * @date 2025/10/13
 */
@RequestMapping("/request")
@Controller
public class RequestController {

    //通过request对象进行数据传递(不建议使用)
    @RequestMapping("/data03")
    public void data03(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setAttribute("name", "德克儿!");
        request.getRequestDispatcher("/WEB-INF/jsps/data.jsp").forward(request, response);
    }

    //通过model对象进行数据传递
    /**
     * SpringMVC会自动创建模型对象传到方法中，我们只需要往这个模型对象中添加数据即可
     * 返回值为字符串,我们可以理解为就是一个视图的名称(写路径即可)
     */
    @RequestMapping("/data01")
    public String data01(Model model){
        model.addAttribute("name","史密斯!");
        User u = new User();
        u.setName("张三x");
    //添加模型数据，key的值为对象的类型首字母小写
        model.addAttribute(u);
        return "/WEB-INF/jsps/data.jsp";
    }

    //通用ModelAndView方式
    @RequestMapping("/data02")
    public ModelAndView data02(){
        ModelAndView mdv = new ModelAndView();
        //设置数据到前台
        mdv.addObject("name", "约什！~");
        User u = new User();
        u.setName("张三");
        //添加模型数据，key的值为对象的类型首字母小写
        mdv.addObject(u);
        //视图名称(路径)
        mdv.setViewName("/WEB-INF/jsps/data.jsp");
        return mdv;
    }
}
